//
//  ZYSubAccountViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/6/14.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYSubAccountViewModel.h"
#import "ZYLoadMoreViewModel.h"
#import "ZYSubAccount.h"
#import "ZYUser.h"
#import "AFNetWorkUtils.h"

@interface ZYSubAccountViewModel()
@property(nonatomic,strong) ZYLoadMoreViewModel *loadViewModel;

/**
 添加子账户
 */
@property(nonatomic,strong) RACCommand *addCommand;
/**
 删除子账户
 */
@property(nonatomic,strong) RACCommand *deleteCommand;

/**
 修改子账户
 */
@property(nonatomic,strong) RACCommand *modifyCommand;
@end

@implementation ZYSubAccountViewModel
//上拉加载更多，下拉刷新
-(ZYLoadMoreViewModel *)loadViewModel{
    if(!_loadViewModel){
        _loadViewModel = [[ZYLoadMoreViewModel alloc] init];
        ZYUser *user = [ZYConfig userInfo];
        NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_SUB_ACCOUNT_LIST_URL];
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"10",@"pageSize",@"1",@"page",nil];
        [params setObject:user.token forKey:@"ssid"];
        _loadViewModel.clazz = [ZYUser class];
        _loadViewModel.params = params;
        _loadViewModel.url = url;
        _loadViewModel.sourceArray = [NSMutableArray array];
        _sourceCommand = _loadViewModel.sourceCommand;
    }
    return _loadViewModel;
}

-(RACCommand *)sourceCommand{
    if(!_sourceCommand){
        _sourceCommand = self.loadViewModel.sourceCommand;
    }
    return _sourceCommand;
}

-(RACCommand *)deleteCommand{
    if(!_deleteCommand){
        _deleteCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            ZYUser *user = [ZYConfig userInfo];
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_SUB_ACCOUNT_DELETE_URL];
            NSString *subAccountId = input;
            NSDictionary *params = @{@"ssid":user.token,@"slaveId":subAccountId};
            RACSignal *netSignal = [[AFNetWorkUtils racPOSTWithURL:url params:params] map:^id(id value) {
                return [NSNumber numberWithBool:YES];
            }];
            return netSignal;
        }];
    }
    return _deleteCommand;
}

-(RACCommand *)addCommand{
    if(!_addCommand){
        _addCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doSaveSubAccount:input type:ZYModifySubAccountTypeAdd subscriber:subscriber];
                return nil;
            }];
        }];
    }
    return _addCommand;
}

-(RACCommand *)modifyCommand{
    if(!_modifyCommand){
        _modifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doSaveSubAccount:input type:ZYModifySubAccountTypeEdit subscriber:subscriber];
                return nil;
            }];
        }];
    }
    return _modifyCommand;
}

-(void)doSaveSubAccount:(ZYUser *)user type:(ZYModifySubAccountType)type subscriber:(id<RACSubscriber>)subscriber{
    //校验数据
    NSString *token = [ZYConfig loginToken];
    BOOL success = [self checkAddData:subscriber withUser:user type:type];
    if(!success){
        return;
    }
    NSString *url = @"";
    NSDictionary *params;
    if(type == ZYModifySubAccountTypeAdd){
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_SUB_ACCOUNT_ADD_URL];
        params = @{@"name":user.username,@"password":user.password,@"ssid":token};
    }else{
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_SUB_ACCOUNT_MODIFY_URL];
        params = @{@"name":user.username,@"newPwd":user.password,@"oldPwd":user.oldPassword,@"ssid":token,@"slaveId":[NSString stringWithFormat:@"%ld",user.userId]};
    }
    [[AFNetWorkUtils racPOSTWithURL:url params:params] subscribeNext:^(id x) {
        //保存用户信息
        NSDictionary *responseObject = x;
        ZYUser *user = [ZYUser modelWithJSON:[responseObject objectForKey:@"result"]];
        [subscriber sendNext:user];
        [subscriber sendCompleted];
    } error:^(NSError *error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];
}


//检查数据
-(BOOL)checkAddData:(id<RACSubscriber>)subscriber withUser:(ZYUser *)user type:(ZYModifySubAccountType)type{
    if(type == ZYModifySubAccountTypeAdd){
        if(NULLString(user.username)){
            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_USERNAME_EMPTY]]];
            [subscriber sendCompleted];
            return NO;
        }
    }else{
        if(NULLString(user.oldPassword)){
            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_OLD_PASSWORD_EMPTY]]];
            [subscriber sendCompleted];
            return NO;
        }
    }
    if(NULLString(user.password)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(![user.password isEqualToString:user.rePassword]){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_INCONSISTENT_PASSWORD]]];
        [subscriber sendCompleted];
        return NO;
    }
    return YES;
}

-(void)setupParams{
    ZYUser *user = [ZYConfig userInfo];
    NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_SUB_ACCOUNT_LIST_URL];
    NSMutableDictionary *params = _loadViewModel.params;
    [params setObject:user.token forKey:@"ssid"];
    _loadViewModel.params = params;
    _loadViewModel.url = url;
}

-(void)loadNewSubAccountList{
    [self setupParams];
    [self.loadViewModel loadNewData];
}

-(void)loadMoreSubAccountList{
    [self setupParams];
    [self.loadViewModel.params setObject:[NSNumber numberWithInteger:self.loadViewModel.pageNum +1] forKey:@"page"];
    [self.loadViewModel loadNextPageData];
}

-(void)addSubAccount:(ZYUser *)subAccount{
    [self.addCommand execute:subAccount];
}

-(void)deleteSubAccount:(NSString *)subAccountId{
    [self.deleteCommand execute:subAccountId];
}

-(void)modifySubAccount:(ZYUser *)subAccount{
    [self.modifyCommand execute:subAccount];
}
@end
